/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.extensionpoints.palette;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IConfigurationElement;

import com.cea.papyrus.core.utils.Debug;

/**
 * 
 */
public class Stack extends MenuElement {
	
	/**
	 * 
	 */
	public final IConfigurationElement	configElement;
	
	/**
	 * 
	 */
	private final Button[] buttons;
	
	/**
	 * 
	 * 
	 * @param ordinal 
	 * @param configElt 
	 * 
	 * @return 
	 */
	public static Stack parse(IConfigurationElement configElt, int ordinal) {
		
		if (!configElt.getName().equals(IConstants.TAG_STACK)) {
			return null;
		}
		
		try {
			return new Stack(configElt);
			
		} catch (Exception e) {
			
			String msg = "Failed to load button stack in "
							+ configElt
								.getDeclaringExtension()
								.getExtensionPointUniqueIdentifier();
			
			Debug.debug(null, msg, channel);
											
			return null;
		}
	}
	
	/**
	 * 
	 * 
	 * @param ordinal 	 * @param configElt 
	 */
	public Stack(IConfigurationElement configElt) {
		this.configElement = configElt;

		// Retrieve menu elements
		IConfigurationElement[] children = configElt.getChildren(IConstants.TAG_BUTTON);
		if (children == null) {
			buttons = null;
			return;
		}

		List<Button> eltList = new ArrayList<Button>();
		// Read properties
		for (int i = 0 ; i < children.length ; i++) {

			Button proxy = Button.parse(children[i], eltList.size());

			if (proxy != null) {
				eltList.add(proxy);
			}
		}

		if (eltList.size() < 1) {
			buttons = null;
		} else {
			buttons = eltList.toArray(new Button[eltList.size()]);
		}
	}
	
	/**
	 * Default constructor.
	 * 
	 * @param uri 	 */
	public Stack() {
		this.configElement = null;
		
		buttons = null;
	}
	
	/**
	 * 
	 * 
	 * @return 
	 */
	public List<Button> getButtonList() {
		List<Button> buttons = new ArrayList<Button>();
		
		Button[] tmp = getButtons();
		if ((tmp == null) || (tmp.length < 1)) {
			return new ArrayList<Button>();
		}
		
		for (int i = 0; i < tmp.length; i++) {
			buttons.add(tmp[i]);
		}
		return buttons;
	}	

	/**
	 * 
	 * 
	 * @return 
	 */
	public Button[] getButtons() {
		return buttons;
	}	
}
